package gw.com.android.ui.views;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gwtsz.android.rxbus.SimpleObserver;
import com.gwtsz.gts2.hx.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import gw.com.android.app.AppMain;
import gw.com.android.greendao.NotifyDataHelper;
import gw.com.android.model.ConfigMenuDeal;
import gw.com.android.model.ConfigType;
import gw.com.android.presenter.AdsConfigPresenter;
import gw.com.android.presenter.AdsData;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.CommonUtils;
import www.com.library.view.RecyclerClickListener;

/**
 * 首页底部自定义View
 *
 * @author yuye.zou
 */
public class MainBottomTabView extends RelativeLayout {

    @BindView(R.id.list_view)
    RecyclerView listView;
    @BindView(R.id.fans_bottom_tabs_button)
    View mLayoutView;
    @BindView(R.id.view_line)
    View mLineView;

    private ButtomTabAdapter mAdapter;
    private DataItemResult mResult;

    private RecyclerClickListener mClickListener = null; //homeTab切换点击监听回调接对象
    private int mSelectPosition = 0;

    public MainBottomTabView(Context context) {
        super(context);
        initView(context);
    }

    public MainBottomTabView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public MainBottomTabView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }

    /**
     * 初始化底部导航控件
     *
     * @author yuye.zou
     */
    private void initView(Context context) {
        if (!this.isInEditMode()) {
            View layout = LayoutInflater.from(context).inflate(R.layout.commom_main_bottom_bar, this, true);
            ButterKnife.bind(this, layout);

            ConfigMenuDeal mMenuDeal = new ConfigMenuDeal();
            mResult = mMenuDeal.getButtomTabTypeList();
            mAdapter = new ButtomTabAdapter(mResult);
            // 线性布局管理器
            GridLayoutManager layoutManager = new GridLayoutManager(context, mAdapter.getItemCount());
            // 设置布局管理器
            listView.setLayoutManager(layoutManager);
            listView.setAdapter(mAdapter);
            AppMain.getApp().getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadRedPoint();
                }
            }, 1000);
        }
    }

    /**
     * 改变选中项
     */
    public DataItemDetail setSelectStr(String title) {
        DataItemDetail item = new DataItemDetail();
        for (int i = 0; i < mResult.getDataCount(); i++) {
            if (title.equals(mResult.getItem(i).getString(ConfigType.CONFIG_TYPE_KEY_TAG))) {
                item = mResult.getItem(i);
                mSelectPosition = i;
                break;
            }
        }
        mAdapter.notifyDataSetChanged();
        return item;
    }

    /**
     * 改变选中项
     */
    public void setSelectPositon(int positon) {
        mSelectPosition = positon;
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 刷新界面
     */
    public void refreshData() {
        mAdapter.notifyDataSetChanged();
    }

    public void refreshTabAd(AdsData adsData) {
        mAdapter.adsData = adsData;
        mAdapter.notifyDataSetChanged();
    }

    public void switchHomeTabIcon(boolean refreshMode) {
        if (mAdapter != null && mAdapter.mList != null) {
            if (mAdapter.mList.getDataCount() > 0) {
                DataItemDetail item = mAdapter.mList.getItem(0);
                //item.setIntValue("iconID", refreshMode ? R.mipmap.a_tabbar_home);
                item.setIntValue("iconID_selected", refreshMode ? R.mipmap.a_tabbar_refresh_p : R.mipmap.a_tabbar_home_p);
                mAdapter.notifyItemChanged(0);
            }
        }
    }

    public void rotateHomeIcon() {
        if (listView != null) {
            RecyclerView.ViewHolder holder = listView.findViewHolderForAdapterPosition(0);
            if (holder != null) {
                ListItemViewHolder mHolder = (ListItemViewHolder) holder;
                ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mHolder.icon, "rotation", 0, 360);
                objectAnimator.setDuration(500);
                objectAnimator.start();
            }
        }
    }

    /**
     * 设置tab切换的点击监听事件
     *
     * @author yuye.zou
     */
    public void setRecyclerClickListener(RecyclerClickListener onHomeTabClick) {
        mClickListener = onHomeTabClick;
    }

    /**
     * Created by reeta.zou on 2017/3/18.
     * 底部布局适配器
     */
    public class ButtomTabAdapter extends RecyclerView.Adapter<ListItemViewHolder> {

        AdsData adsData;
        private DataItemResult mList;//底部显示的直接数据来源
        int unReadCount = 0;

        /**
         * 初始化界面数据
         */
        ButtomTabAdapter(DataItemResult list) {
            mList = list;
            adsData = AdsConfigPresenter.getInstance().getAd(AdsConfigPresenter.TYPE_TAB_TRADE);
        }

        @NonNull
        @Override
        public ListItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.commom_main_bottom_item, parent, false);
            return new ListItemViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ListItemViewHolder holder, int position) {
            final DataItemDetail mItem = getItem(position);
            if (null != mItem) {
                String key = mItem.getString(ConfigType.CONFIG_TYPE_KEY_TAG);
                if (ConfigType.TAB_TRADE_TAG.equals(key)) {
                    //  交易tab 游客跟N用户显示不同的ICON
                    if (adsData != null && !adsData.adPics.isEmpty()) {
                        AdsData.PicData picData = adsData.adPics.get(0);
                        holder.icon.setVisibility(GONE);
                        holder.name.setVisibility(GONE);
                        holder.trick.setVisibility(VISIBLE);
                        Glide.with(getContext()).load(picData.url).into(holder.trick);
                    } else {
                        refreshHolder(holder, mItem, position);
                    }
                } else {
                    refreshHolder(holder, mItem, position);
                }
                final int index = position;
                holder.itemView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (CommonUtils.isFastDoubleClick()) {
                            return;
                        }
                        if (null != mClickListener) {
                            mClickListener.onClick(index, mItem);
                        }
                    }
                });
            }
        }

        private void refreshHolder(ListItemViewHolder holder, DataItemDetail mItem, int position) {
            holder.icon.setVisibility(VISIBLE);
            holder.name.setVisibility(VISIBLE);
            holder.trick.setVisibility(GONE);

            holder.icon.setSelected(position == mSelectPosition);
            holder.name.setSelected(position == mSelectPosition);
            holder.name.setText(mItem.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));

            int iconID = mItem.getInt("iconID");
            int iconID_selected = mItem.getInt("iconID_selected");
            if (iconID != 0) {
                holder.icon.setImageDrawable(generateSeletor(iconID, iconID_selected));
            } else {
                holder.icon.setImageResource(R.mipmap.a_me_default);
            }
            if ((unReadCount > 0) && mItem.getString(ConfigType.CONFIG_TYPE_TITLE_TAG).equals(AppMain.getAppString(R.string.main_menu_item_me))) {
                holder.tipV.setVisibility(VISIBLE);
            } else {
                holder.tipV.setVisibility(GONE);
            }
        }

        @Override
        public int getItemCount() {
            if (null != mList) {
                return mList.getDataCount();
            }
            return 0;
        }

        public DataItemDetail getItem(int position) {
            if (position < 0 || mList == null || position >= mList.getDataCount()) {
                return null;
            }
            return mList.getItem(position);
        }

        private Drawable generateSeletor(int resId, int resIdSelected) {
            StateListDrawable drawable = new StateListDrawable();
            drawable.addState(new int[]{android.R.attr.state_selected}, getResources().getDrawable(resIdSelected));
            drawable.addState(new int[]{}, getResources().getDrawable(resId));
            return drawable;
        }

    }

    class ListItemViewHolder extends RecyclerView.ViewHolder {
        //产品名称
        TextView name;
        ImageView icon;
        //红点
        ImageView tipV;
        ImageView trick; // 花里胡哨的特殊样式

        ListItemViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.tab_name);
            icon = itemView.findViewById(R.id.tab_icon);
            tipV = itemView.findViewById(R.id.tip_icon);
            trick = itemView.findViewById(R.id.tab_trick);
        }

    }

    private void loadRedPoint() {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                e.onNext(NotifyDataHelper.getUnreadCount());
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new SimpleObserver<Integer>() {
            @Override
            public void onNext(Integer result) {
                refreshRedPoint(result);
            }
        });
    }

    public void refreshRedPoint(int count) {
        if (mAdapter != null) {
            mAdapter.unReadCount = count;
            mAdapter.notifyDataSetChanged();
        }
    }

    public void onNightMode(boolean isNight) {
        if (isNight) {
            mLayoutView.setBackgroundColor(getResources().getColor(R.color.color_night_bg));
            mLineView.setBackgroundColor(getResources().getColor(R.color.color_quote_h));
        } else {
            mLayoutView.setBackgroundColor(getResources().getColor(R.color.color_e));
            mLineView.setBackgroundColor(getResources().getColor(R.color.color_tabbar_line));
        }
    }

}
